package arithmetic;

public class QuickSort4 {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            // 找到划分元素的索引
            int pivotIndex = partition(arr, low, high);

            // 对划分元素左边的子数组进行快速排序
            quickSort(arr, low, pivotIndex - 1);

            // 对划分元素右边的子数组进行快速排序
            quickSort(arr, pivotIndex + 1, high);
        }
    }

    private static int partition(int[] arr, int low, int high) {
        // 选择最后一个元素作为基准
        int pivot = arr[high];
        int i = (low - 1);

        for (int j = low; j <= high - 1; j++) {
            // 当前元素小于或等于基准
            if (arr[j] <= pivot) {
                i++;

                // 交换arr[i]和arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // 交换arr[i+1]和arr[high]（或 pivot）
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    public static void main(String[] args) {
        int[] arr = {-10, 7, 8, 9, 100, 5};
        int n = arr.length;
        quickSort(arr, 0, n-1);
        System.out.println("Sorted array: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

